<template>
  <div :style="{ height }">
    <CodeMirrorEditor
      :value="getValue"
      @change="handleValueChange"
      :mode="mode"
      :readonly="readonly"
      :bordered="bordered"
      :config="config"
      class="!h-full"
    />
  </div>
</template>

<script setup>
  import { computed } from 'vue';
  import CodeMirrorEditor from './codemirror/CodeMirror.vue';
  import { isString } from 'lodash-es';
  import { MODE } from './typing';

  const props = defineProps({
    value: { type: [Object, String], default: '' },
    mode: {
      type: String,
      default: MODE.JS,
      validator(value) {
        return Object.values(MODE).includes(value);
      },
    },
    readonly: { type: Boolean },
    autoFormat: { type: Boolean, default: true },
    bordered: { type: Boolean, default: false },
    config: { type: Object, default: () => ({}) },
    height: { type: String, default: '360px' },
  });

  const emit = defineEmits(['change', 'update:value', 'format-error']);

  const getValue = computed(() => {
    const { value, mode, autoFormat } = props;
    if (!autoFormat || mode !== MODE.JSON) {
      return value || '';
    }
    let result = value;
    if (isString(value)) {
      try {
        result = JSON.parse(value);
      } catch (e) {
        emit('format-error', value);
        return value;
      }
    }
    return JSON.stringify(result, null, 2);
  });

  function handleValueChange(v) {
    emit('update:value', v);
    emit('change', v);
  }
</script>

<style>
  .CodeMirror {
    height: 100% !important;
  }
</style>
